package com.example.udp2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class UdpServer implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(UdpServer.class);


    @Override
    public void run() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(8090);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        byte[] buff = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buff, 1024);
        while (true){
            try {
                //接收消息
                assert ds != null;
                ds.receive(dp);
                InetAddress address =dp.getAddress();
                int port = dp.getPort();
                logger.info("-----------------------连接的主机名："+ address+"-------端口号是"+ port);
                //得到传送过来的数据
                byte[]buffs = dp.getData();
                String data = byte2Hex(buffs,dp.getLength());
                String newDate = hexStringToString(data);
                logger.info("------------------------解密得到的数据是"+newDate);
                StringBuilder s = new StringBuilder();
                for (int i=0;i<newDate.length();i++){
                    char c = newDate.charAt(i);
                    if(Character.isLowerCase(c)){
                        s.append(Character.toUpperCase(c));
                    }else {
                        s.append(Character.toLowerCase(c));
                    }
                }
                logger.info("------------------------------转化过的数据是" +s.toString());
                byte [] bytes = s.toString().getBytes();
                DatagramPacket dp2 = new DatagramPacket(bytes,bytes.length, new InetSocketAddress(address,port));
                ds.send(dp2);
            }  catch (IOException e) {
                e.printStackTrace();
                logger.info("消息异常，错误消息是"+e);
            }
        }
    }
    /*
      二进制转成16进制
     */
    public static String byte2Hex(byte[] bytes, int length) {
        StringBuilder stringBuffer = new StringBuilder();
        String temp ;
        for (int i = 0; i < length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    //16进制字符串转换成字符串
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, StandardCharsets.UTF_8);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }
}
